﻿using Core.Interfaces;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using Core.Entities;

namespace Infrastructure.Data
{
    /// <summary>
    /// 应用数据库上下文
    /// </summary>
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
        {
        }

        // 在这里添加DbSet，例如：
        // public DbSet<User> Users { get; set; }
        // 但是，我们也可以不在这里添加，而是通过OnModelCreating中自动扫描，但为了IntelliSense和显式使用，可以添加。

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            // 自动应用所有实体配置（从当前程序集）
            modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());

            // 全局查询过滤器 - 软删除
            foreach (var entityType in modelBuilder.Model.GetEntityTypes()
                .Where(e => typeof(IEntity<>).IsAssignableFrom(e.ClrType)))
            {
                var method = typeof(ApplicationDbContext)
                    .GetMethod(nameof(ApplyGlobalFilters), BindingFlags.Instance | BindingFlags.NonPublic)
                    .MakeGenericMethod(entityType.ClrType);
                method.Invoke(this, new object[] { modelBuilder });
            }
        }

        /// <summary>
        /// 应用全局过滤器（软删除）
        /// </summary>
        /// <typeparam name="TEntity">实体类型</typeparam>
        /// <param name="modelBuilder">模型构建器</param>
        private void ApplyGlobalFilters<TEntity>(ModelBuilder modelBuilder) where TEntity : class
        {
            modelBuilder.Entity<TEntity>().HasQueryFilter(e => !EF.Property<bool>(e, "IsDeleted"));
        }
    }
}